package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.base.*
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler

class YouYiYan :  BaseBookHandler() {

    override val host: String = "www.youyiyan.com"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val nameElement = document.select(".bookinfo a")[0]
        val name = nameElement.text()

        // #main > div.cont_1000 > div.bookinfo.m10.clearfix > div.info > p:nth-child(2) > span
        // 文 / 烽火戏诸侯
        val author =
            document.select("#main > div.cont_1000 > div.bookinfo.m10.clearfix > div.info > p:nth-child(2) > span")
                .text().split("/")[1].trim()

        // #main > div.cont_1000 > div.bookinfo.m10.clearfix > div.cont > div.bookimg > a > img
        val coverUrl =
            document.select("#main > div.cont_1000 > div.bookinfo.m10.clearfix > div.cont > div.bookimg > a > img")[0].attr(
                "src"
            )

        // #bookindex
        val menuUrlHref = document.select("#bookindex").attr("href")
        val menuUrl = makeUrl(menuUrlHref)

        return BookMetaEntity(name, url, menuUrl, author, coverUrl)
    }

    @Suppress("HttpUrlsUsage")
    private fun makeUrl(menuUrlHref: String) = "http://$host$menuUrlHref"

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val result = mutableListOf<ChapterMetaEntity>()

        // #main > div.cont_1000 > div.chapterlist > ul > li > a
        val chapterList = document.select("#main > div.cont_1000 > div.chapterlist > ul > li > a")

        for ((index, element) in chapterList.withIndex()) {
            // <li><a href="/chapter/view/27395.html" title="第四十三章">第四十三章</a></li>
            val chapterUrlHref = element.select("a").attr("href")
            val chapterUrl = makeUrl(chapterUrlHref)
            val chapterName = element.select("a").text()

            val chapterMeta = ChapterMetaEntity(chapterName, index, chapterUrl, element)
            result.add(chapterMeta)
        }


        return result
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val document = chapterMetaEntity.url.toHttpUrl().toDocument() ?: return null
        // #content 的 文本内容
        val content = document.select("#content").first()?.wholeText() ?: return null

        // 开头有：<< 马上记住有一眼,,如果被任意浏/览/器转/码,阅读体验极差请退出转/码阅读. >> 需要去掉
        val contentWithoutHead = content.replaceFirst("马上记住有一眼,,如果被任意浏/览/器转/码,阅读体验极差请退出转/码阅读.", "")

        return ChapterEntity(chapterMetaEntity.name, chapterMetaEntity.index, contentWithoutHead)
    }
}